package com.zdkj.subway.check.controller.stationTiecketManager.xianWngCJXXQR.shouRuJS;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zdkj.admin.api.entity.SysUser;
import com.zdkj.subway.check.entity.Page;
import com.zdkj.subway.check.entity.SwAuInternetTicketEquipment;
import com.zdkj.subway.check.entity.SwStInternetTicketEquipmentDetails;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.SwAuInternetTicketEquipmentMapper;
import com.zdkj.subway.check.mapper.SwStInternetTicketEquipmentDetailsMapper;
import com.zdkj.subway.check.mapper.SwStInternetTicketEquipmentMapper;
import com.zdkj.subway.check.mapper.SysUserMapper;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.util.ObejctFieldsValueNotNull;
import com.zdkj.subway.check.util.UserInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 线网下的收入结算-互联网售票机
 */
@RequestMapping("/xw_js_hlw")
@RestController
@Slf4j
public class Xw_HLW_shouJieSuanCtrl {

    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    SwStInternetTicketEquipmentMapper swStInternetTicketEquipmentMapper;
    @Resource
    SwAuInternetTicketEquipmentMapper swAuInternetTicketEquipmentMapper;
    @Resource
    SwStInternetTicketEquipmentDetailsMapper swStInternetTicketEquipmentDetailsMapper;
    /**
     * 互联网售票机待提交主页
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getXw_hlw_shouJieSuan_waitSubmit")
    @ApiOperation(value = "互联网售票机待提交主页", notes = "互联网售票机待提交主页")
    public Page getXw_hlw_shouJieSuan_waitSubmit(Page page,@RequestParam Map<String,String> param) {
        List<Map<String,Object>> tvm_shouJieSuan_waitSubmit=swStInternetTicketEquipmentMapper.getXw_hlw_shouJieSuan_waitSubmit(param);
        page.setData(tvm_shouJieSuan_waitSubmit);
        return page;
    }


    /**
     * 预览数据
     * @param param
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getXw_hlw_shouJieSuan_preview")
    @ApiOperation(value = "预览数据", notes = "预览数据")
    public Result getXw_hlw_shouJieSuan_preview(@RequestParam Map<String,Object> param) throws ParseException, SQLException {
        Result res=new Result(ResultDetailMsg.OK);
        try{
            List<SwStInternetTicketEquipmentDetails> swStInternetTicketEquipmentDetails = swStInternetTicketEquipmentDetailsMapper.selectByMap(param);
            res.setData(swStInternetTicketEquipmentDetails);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
        }
        return res;
    }

    /**
     * 互联网售票机提交
     * @param ids 需要添加的数据id
     * @param attendancePersonJobNo 值班站长
     * @return
     * @throws ParseException
     */
    @RequestMapping("/hlwSubmitData")
    @ApiOperation(value = "互联网售票机提交", notes = "互联网售票机提交")
    @Transactional(rollbackFor = Exception.class)
    public Result hlwSubmitData(String ids,String attendancePersonJobNo) throws ParseException {
        Result res=new Result(ResultDetailMsg.OK);
        try {
            QueryWrapper<SwStInternetTicketEquipmentDetails> queryWrapper=new QueryWrapper<>();
            queryWrapper.in("id",ids.split(","));

            QueryWrapper<SysUser> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.in("user_code",attendancePersonJobNo.split(","));
            List<Map<String, Object>> maps = sysUserMapper.selectMaps(queryWrapper1);
            if(maps.size()<=0){
                throw new Exception("未找到人员编码："+attendancePersonJobNo);
            }
            Integer user_id = (Integer) maps.get(0).get("user_id");
            String nikename = (String) maps.get(0).get("nikename");

            List<SwStInternetTicketEquipmentDetails> swStInternetTicketEquipments = swStInternetTicketEquipmentDetailsMapper.selectList(queryWrapper);
            for(SwStInternetTicketEquipmentDetails swStInternetTicketEquipment:swStInternetTicketEquipments){

                //    （修改条件：线路站点、设备编号、收益日期）
                //  不存在insert
                SwAuInternetTicketEquipment swAuInternetTicketEquipment1 = swAuInternetTicketEquipmentMapper.selectOne(
                        Wrappers.<SwAuInternetTicketEquipment>lambdaQuery()
                                .eq(SwAuInternetTicketEquipment::getLineCode, swStInternetTicketEquipment.getLineCode())
                                .eq(SwAuInternetTicketEquipment::getStationCode, swStInternetTicketEquipment.getStationCode())
                                .eq(SwAuInternetTicketEquipment::getEquipmentCode, swStInternetTicketEquipment.getEquipmentCode())
                                .eq(SwAuInternetTicketEquipment::getRevenueDate, swStInternetTicketEquipment.getRevenueDate()));

                if(swAuInternetTicketEquipment1 ==null){

                    SwAuInternetTicketEquipment swAuInternetTicketEquipment =new SwAuInternetTicketEquipment();
                    swAuInternetTicketEquipment.setLineCode(swStInternetTicketEquipment.getLineCode());
                    swAuInternetTicketEquipment.setStationCode(swStInternetTicketEquipment.getStationCode());
                    SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
                    swAuInternetTicketEquipment.setStartTime(dff.format(swStInternetTicketEquipment.getStartTime()));
                    swAuInternetTicketEquipment.setEndTime(dff.format(swStInternetTicketEquipment.getEndTime()));
                    swAuInternetTicketEquipment.setTotalNumberSales(swStInternetTicketEquipment.getSaleNumber());
					swAuInternetTicketEquipment.setRemark(swStInternetTicketEquipment.getRemark());

                    swAuInternetTicketEquipment.setSubtotalTotal(swStInternetTicketEquipment.getTotalSaleAmount());
                    long SettlementPeriod=(swStInternetTicketEquipment.getEndTime().getTime()-swStInternetTicketEquipment.getStartTime().getTime())/(24*60*60*1000);
                    swAuInternetTicketEquipment.setSettlementPeriod(Integer.parseInt(String.valueOf(SettlementPeriod)));
                    swAuInternetTicketEquipment.setApprovalStatus(0);
                    swAuInternetTicketEquipment.setIsAddReprotError("0");
                    swAuInternetTicketEquipment.setCreatorId(UserInfo.getId());
                    swAuInternetTicketEquipment.setCreatorName(UserInfo.getUserName());
                    swAuInternetTicketEquipment.setCreateTime(new Date());

                    swAuInternetTicketEquipment.setPassengerAttendantId(UserInfo.getId());
                    swAuInternetTicketEquipment.setPassengerAttendantJobNo(UserInfo.getUserCode());
                    swAuInternetTicketEquipment.setPassengerAttendantName(UserInfo.getName());

                    swAuInternetTicketEquipment.setEquipmentCode(swStInternetTicketEquipment.getEquipmentCode());
                    swAuInternetTicketEquipment.setEquipmentName(swStInternetTicketEquipment.getEquipmentName());
                    swAuInternetTicketEquipment.setRevenueDate(dff.format(swStInternetTicketEquipment.getRevenueDate()));
                    swAuInternetTicketEquipment.setReportModifyStatus(swStInternetTicketEquipment.getReportModifyStatus());


                    swAuInternetTicketEquipment.setAttendancePersonId(user_id);
                    swAuInternetTicketEquipment.setAttendancePersonJobNo(attendancePersonJobNo);

                    swAuInternetTicketEquipment.setAttendancePersonName(nikename);

                    swAuInternetTicketEquipment =(SwAuInternetTicketEquipment)ObejctFieldsValueNotNull.setValueNoNull(SwAuInternetTicketEquipment.class, swAuInternetTicketEquipment);
                    swAuInternetTicketEquipment =(SwAuInternetTicketEquipment)ObejctFieldsValueNotNull.jisuanBigDicmalMulti(SwAuInternetTicketEquipment.class, swAuInternetTicketEquipment,100d);

                    swAuInternetTicketEquipmentMapper.insertSwAuInputInternetTicketEquipment(swAuInternetTicketEquipment);

                    swStInternetTicketEquipment.setSwAuInternetTicketId(swAuInternetTicketEquipment.getId());
                    //更新互联网售票机详情表
                    updateInternetTicketEquipmentDetails(swStInternetTicketEquipment,attendancePersonJobNo);

                }else {
                    //存在就update发售数量，发售金额、差异金额、差异数量
                    SwAuInternetTicketEquipment swAuInternetTicketEquipment =new SwAuInternetTicketEquipment();
                    swAuInternetTicketEquipment.setId(swAuInternetTicketEquipment1.getId());
                    swAuInternetTicketEquipment.setTotalNumberSales(swStInternetTicketEquipment.getSaleNumber());
                    swAuInternetTicketEquipment.setSubtotalTotal(swStInternetTicketEquipment.getTotalSaleAmount());
					swAuInternetTicketEquipment.setRemark(swStInternetTicketEquipment.getRemark());
					//存在的时候金额乘100
                    swAuInternetTicketEquipment =(SwAuInternetTicketEquipment)ObejctFieldsValueNotNull.jisuanBigDicmalMulti(SwAuInternetTicketEquipment.class, swAuInternetTicketEquipment,100d);
                    swAuInternetTicketEquipmentMapper.updateById(swAuInternetTicketEquipment);
                    //更新互联网售票机详情表
                    updateInternetTicketEquipmentDetails(swStInternetTicketEquipment,attendancePersonJobNo);
                }


            }

        }catch (Exception e){
            log.error("提交失败",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("提交失败");
        }
      return res;
    }

    /**
     * 更新互联网售票机详情表
     * @param swStInternetTicketEquipment
     * @param attendancePersonJobNo
     * @throws Exception
     */
    public void updateInternetTicketEquipmentDetails(SwStInternetTicketEquipmentDetails swStInternetTicketEquipment, String attendancePersonJobNo) throws Exception {
        QueryWrapper<SysUser> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.in("user_code",attendancePersonJobNo.split(","));
        List<Map<String, Object>> maps = sysUserMapper.selectMaps(queryWrapper1);
        if(maps.size()<=0){
            throw new Exception("未找到人员编码："+attendancePersonJobNo);
        }
        Integer user_id = (Integer) maps.get(0).get("user_id");
        String nikename = (String) maps.get(0).get("nikename");

        swStInternetTicketEquipment.setApprovalStatus(1);
        swStInternetTicketEquipment.setUpdateTime(new Date());
        swStInternetTicketEquipment.setPassengerAttendantId(UserInfo.getId());
        swStInternetTicketEquipment.setPassengerAttendantJobNo(UserInfo.getUserCode());
        swStInternetTicketEquipment.setPassengerAttendantName(UserInfo.getName());

        swStInternetTicketEquipment.setAttendancePersonId(user_id);
        swStInternetTicketEquipment.setAttendancePersonJobNo(attendancePersonJobNo);
        swStInternetTicketEquipment.setAttendancePersonName(nikename);

        swStInternetTicketEquipmentDetailsMapper.updateById(swStInternetTicketEquipment);
    }
}
